package org.carabiner.infinitest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 
 * @author <a href="mailto:benrady@gmail.com"Ben Rady</a>
 *
 */
public class FilterList 
{
  private List<Pattern> filters;
  private File file;
  
  public FilterList(File filterFile) throws IOException
  {   
    file = filterFile;
    updateFilterList();
  }
  
  public FilterList()
  {
    filters = new ArrayList<Pattern>();
  }

  public void updateFilterList() throws IOException
  {
    filters = new ArrayList<Pattern>();
    if (file.exists())
    {
      FileReader fileReader = new FileReader(file);
      try
      {        
        BufferedReader reader = new BufferedReader(fileReader);
        String line = null;
        do
        {
          line = reader.readLine();
          if (line != null)
          {
            boolean isComment = line.startsWith("!") || line.startsWith("#");
            if (!isComment)
            {
              filters.add(Pattern.compile(line));
            }
          }
        } while (line != null);
      } finally
      {
        fileReader.close();
      }
    }    
  }

  public boolean match(String className)
  {
    for (Pattern pattern : filters)
    {
      if (pattern.matcher(className).find())
        return true;
    }
    return false;
  }

  public void addFilter(String regex) throws IOException
  {    
    filters.add(Pattern.compile(regex));
  }
  
  public void appendFilter(String regex) throws IOException
  {    
    PrintWriter writer = new PrintWriter(new FileOutputStream(file, true));
    try
    {
      writer.println(regex);
    }
    finally
    {
      writer.close();
    }
    updateFilterList();
  }
}
